package com.tonicgb.service;

import com.tonicgb.api.front.request.RegisterThirdUserRequest;
import com.tonicgb.api.front.request.WechatBindPhoneRequest;
import com.tonicgb.api.front.response.LoginResponse;
import com.tonicgb.model.User;
import com.tonicgb.model.UserToken;
import com.tonicgb.shared.common.constants.Constants;
import com.tonicgb.shared.common.enums.WechatCodeEnum;
import com.tonicgb.shared.exception.ApiException;
import com.tonicgb.shared.util.JWTUtil;

import com.tonicgb.wechat.response.WeChatProgramAuthorizeResponse;
import com.tonicgb.wechat.service.WechatMiniProgram;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * @author zhaiyujin
 * @date 2021-10-05 00:49:59
 * @说明 用户中心
 */
@Service
public class UserCenterService {

 @Autowired
 private WechatMiniProgram wechatMiniProgram;

 @Autowired
 private UserTokenService userTokenService;

 @Autowired
 private UserService userService;


/*
 * @Description: 小程序授权登录
 * @param code:
 * @param request:
 * @return java.lang.Object
 * @Author: zhaiyujin
 * @Date: 2021/10/5
 */
 public Object weChatAuthorizeProgramLogin(String code, RegisterThirdUserRequest request) {

  WeChatProgramAuthorizeResponse response = wechatMiniProgram.programAuthorize(code);
  User user = programLogin(response.getOpenId(), response.getUnionId(), request);
  //通过用户id获取登录token信息
  LoginResponse loginResponse = new LoginResponse();
       try {
        user.setPwd(null);
        loginResponse.setWechatResponse(response);
        loginResponse.setToken(JWTUtil.createToken(user));
        loginResponse.setUser(user);
       } catch (Exception exception) {
        throw new ApiException(exception.getMessage());
       }
  return loginResponse;
 }

/**
 * @Description: 微信授权绑定手机号
 * @param wechatBindPhoneRequest: 解密请求参数
 * @return java.lang.String
 * @Author: zhaiyujin
 * @Date: 2021/10/5
 */
 public boolean weChatAuthorizeBindPhone(WechatBindPhoneRequest wechatBindPhoneRequest){


 String phone=  wechatMiniProgram.getPhone(wechatBindPhoneRequest.getSessionKey(),wechatBindPhoneRequest.getEncryptedData(),wechatBindPhoneRequest.getIv());
  if (phone == null) {
   throw new ApiException(WechatCodeEnum.GET_PHONE_ERROR);
  }
  UserToken userToken=userTokenService.checkToken(wechatBindPhoneRequest.getOpenId(), Constants.THIRD_LOGIN_TOKEN_TYPE_PROGRAM);

  if (userToken == null) {
   throw new ApiException(WechatCodeEnum.OPENID_NO_EXIST);
  }
  return userService.updateById(new User().setId(userToken.getUid()).setPhone(phone));

}




/**
 * @Description:小程序登录逻辑
 * @param openId:
 * @param unionId:
 * @param request:
 * @return com.tonicgb.model.User
 * @Author: zhaiyujin
 * @Date: 2021/10/5
 */
 private User programLogin(String openId, String unionId, RegisterThirdUserRequest request) {
  try {
   //检测是否存在
   UserToken userToken = userTokenService.checkToken(openId, Constants.THIRD_LOGIN_TOKEN_TYPE_PROGRAM);
   //数据库存在openId直接返回
   if (null != userToken) {
    return userService.getById(userToken.getUid());
   }
   //数据不存在openId ,查询unionID，存在则放返回
   if (StringUtils.isNotBlank(unionId)) {
    userToken = userTokenService.checkToken(unionId, Constants.THIRD_LOGIN_TOKEN_TYPE_PROGRAM);
    if (null != userToken) {
     return userService.getById(userToken.getUid());
    }
   }

   //TODO 是否需要强制注册用户，1 强制注册，2 需要返回数据给前端，让其输入手机号和验证码
   User user = userService.registerByThird(request, Constants.USER_LOGIN_TYPE_PROGRAM);

   userTokenService.bind(openId, Constants.THIRD_LOGIN_TOKEN_TYPE_PROGRAM, user.getId());
   //unionId有就绑定
   if (StringUtils.isNotBlank(unionId)) {
    userTokenService.bind(unionId, Constants.THIRD_LOGIN_TOKEN_TYPE_UNION_ID, user.getId());
   }
   return user;

  } catch (Exception e) {
   throw new ApiException(e.getMessage());
  }

 }





}
